package com.limit.model;

import java.util.List;

import cn.rj.util.security.MD5;

import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.ehcache.CacheKit;
import com.limit.constant.Constant;
/**
 * 后台用户<br/>
 * @author maoyun(maoyun0903@163.com)
 * @date 2014-3-27 下午04:34:03 
 * @version V1.0
 */
public class Admin extends Model<Admin> {

	/**
	 * @Fields serialVersionUID : TODO
	 */
	private static final long serialVersionUID = 1L;
	public final static Admin dao = new Admin();
	
	/**
	 * 检测是否存在此用户(不包括已被禁用的账户)
	 */
	private Admin _find(String name , String password){
		String sql = "select * from admin where login_name=? and password=? and disable=?";
		password = MD5.UTF8Encode(password);
		return super.findFirst(sql, name,password,-1);
	}
	
	/**
	 * 检查账户是否存在
	 */
	public boolean checkAccount(String name , String password){
		Admin admin = this._find(name , password);
		return admin == null ? false : true;
	}
	
	/**
	 * 获取Admin，若不存在则返回NULL
	 */
	public Admin getAccount(String name , String password){
		return this._find(name, password);
	}
	
	/**
	 * 检查是否存在用户名为：username的记录
	 */
	public boolean isExistUserName(String username){
		
		Admin admin = Admin.dao.findFirst("select * from admin where username=?",username);
		
		return admin == null ? false : true;
		
		
	}
	
	/**
	 * 注：不包括禁用的账户
	 * actor_id <=0 : 取所有记录 <br/>
	 * actor_id >0  : 以actor_id为条件查询记录
	 */
	public List<Admin> getList(long actor_id){
		StringBuilder sql = new StringBuilder("select * from admin where ");
		if(actor_id <= 0){
			sql.append("disable=?");
			return Admin.dao.find(sql.toString(), -1);
		}else{
			sql.append("actor_id=? and disable=?");
			return Admin.dao.find(sql.toString(),actor_id,-1);
		}
	}
	
	/**
	 * 不包括超级管理员的不被禁用的后台账户
	 */
	public List<Admin> getListExceptAdmin(){
		
		return Admin.dao.find("select * from admin where actor_id !=? and disable=?",1,-1);
	}
	
	/**
	 * 从缓存得出Admin对象
	 */
	public Admin getCacheAdmin(long admin_id){
		
		List<Admin> caches = CacheKit.get(Constant.CacheActor, Constant.CacheActor);
		Admin admin = null;
		if(null == caches || caches.isEmpty()){
			admin = Admin.dao.findFirst("select * from admin where id=?",admin_id);
		}else{
			for (Admin cp : caches) {
				admin = cp;
				if(cp.getLong("id") == admin_id){
					break;
				}
			}
		}
		return admin;
		
	}
}
